package application.exportimport;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Superclass of all xml generators for servers of type of zbozi.cz, heureka.cz etc.
 */
public abstract class AbstractXmlGenerator {

    /**
     * Xml file suffix (.xml)
     */
    public static final String XML_FILE_SUFFIX = ".xml";
    /**
     * Directory path where should be xml file generated.
     */
    protected String directory;

    /**
     * Create file where to should be xml generated.
     *
     * @return created File which psysically exist on HDD.
     * @throws IOException
     */
    protected abstract File createFile() throws IOException;

    /**
     * Createa and fill xml wrapper with annotation XmlRoot.
     *
     * @return wrapper
     */
    protected abstract AbstractXmlWrapper createAndFillXMLWrapper();

    /**
     * Setter for directory path where should be xml file generated.
     *
     * @param directory
     */
    protected void setDirectoryPath(String directory) {
        this.directory = directory;
    }

    /**
     * Call methods createAndFillXMLWrapper() and createFile() and than run marshal.
     *
     * @throws FileNotFoundException
     * @throws JAXBException
     * @throws IOException
     */
    protected void generate() throws FileNotFoundException, JAXBException, IOException {
        AbstractXmlWrapper wrapper = createAndFillXMLWrapper();
        File file = createFile();
        FileOutputStream fos = new FileOutputStream(file);

        JAXBContext jaxbContext = JAXBContext.newInstance(wrapper.getClass());
        Marshaller m = jaxbContext.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(wrapper, fos);
    }
}

